package com.doublethread.easymart.modules.comment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doublethread.easymart.common.exception.CommentException;
import com.doublethread.easymart.common.exception.FileException;
import com.doublethread.easymart.common.result.PageResult;
import com.doublethread.easymart.common.utils.Base64MultipartFile;
import com.doublethread.easymart.common.utils.OssUtils;
import com.doublethread.easymart.modules.comment.dto.*;
import com.doublethread.easymart.modules.comment.entity.ProductComment;
import com.doublethread.easymart.modules.comment.mapper.ProductCommentMapper;
import com.doublethread.easymart.modules.comment.service.CommentService;
import com.doublethread.easymart.modules.comment.vo.AdminCommentVO;
import com.doublethread.easymart.modules.comment.vo.CommentStatisticsVO;
import com.doublethread.easymart.modules.comment.vo.CommentVO;
import com.doublethread.easymart.modules.order.entity.OrderItem;
import com.doublethread.easymart.modules.order.mapper.OrderItemMapper;
import com.doublethread.easymart.modules.product.entity.Product;
import com.doublethread.easymart.modules.product.mapper.ProductMapper;
import com.doublethread.easymart.modules.user.entity.User;
import com.doublethread.easymart.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品评价服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<ProductCommentMapper, ProductComment> implements CommentService {

    private final UserMapper userMapper;
    private final ProductMapper productMapper;
    private final OrderItemMapper orderItemMapper;
    private final OssUtils ossUtils;

    @Override
    public Page<CommentVO> getProductComments(Long productId, CommentQueryDTO queryDTO) {
        log.info("获取商品评价列表");

        // 构建查询条件
        LambdaQueryWrapper<ProductComment> queryWrapper = new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getProductId, productId)
                .eq(ProductComment::getStatus, 1) // 只显示已发布的评论
                .eq(ProductComment::getIsDeleted, 0)
                .orderByDesc(ProductComment::getCreateTime);

        // 评分筛选
        if (queryDTO.getRating() != null) {
            queryWrapper.eq(ProductComment::getRating, queryDTO.getRating());
        }

        // 分页查询
        Page<ProductComment> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        Page<ProductComment> commentPage = this.page(page, queryWrapper);

        // 转换为VO并返回
        return (Page<CommentVO>) commentPage.convert(this::convertToCommentVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createComment(Long userId, CommentCreateDTO commentCreateDTO) {
        log.info("创建商品评价");

        // 1. 验证商品是否存在
        Product product = productMapper.selectById(commentCreateDTO.getProductId());
        if (product == null) {
            CommentException.commentProductNotFound();
        }

        // 2. 检查用户是否已经对该订单中的该商品评价过（防止重复评论）
        LambdaQueryWrapper<ProductComment> existingWrapper = new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getUserId, userId)
                .eq(ProductComment::getProductId, commentCreateDTO.getProductId())
                .eq(ProductComment::getIsDeleted, 0);

        // 如果提供了订单ID，则检查该订单中的商品是否已评价
        if (commentCreateDTO.getOrderId() != null) {
            existingWrapper.eq(ProductComment::getOrderId, commentCreateDTO.getOrderId());
        }

        long existingCount = this.count(existingWrapper);

        if (existingCount > 0) {
            CommentException.commentAlreadyExists();
        }

        // 5. 处理评论图片上传（如果有Base64图片数据）
        List<String> finalImageUrls = new ArrayList<>();
        if (commentCreateDTO.getImages() != null && !commentCreateDTO.getImages().isEmpty()) {
            for (String imageData : commentCreateDTO.getImages()) {
                if (imageData != null && imageData.startsWith("data:image/")) {
                    // Base64格式，需要上传到OSS
                    try {
                        String imageUrl = uploadCommentImage(imageData);
                        finalImageUrls.add(imageUrl);
                        log.info("评论图片上传成功: userId={}, imageUrl={}", userId, imageUrl);
                    } catch (Exception e) {
                        log.error("评论图片上传失败: userId={}, error={}", userId, e.getMessage());
                        // 图片上传失败不影响评论创建，跳过该图片
                    }
                } else if (imageData != null && imageData.startsWith("http")) {
                    // URL格式，直接使用
                    finalImageUrls.add(imageData);
                }
            }
        }

        // 3. 创建评论 - 使用Builder模式
        ProductComment comment = ProductComment.builder()
                .userId(userId)
                .productId(commentCreateDTO.getProductId())
                .orderId(commentCreateDTO.getOrderId())
                .content(commentCreateDTO.getContent())
                .rating(commentCreateDTO.getRating())
                .isAnonymous(commentCreateDTO.getIsAnonymous())
                .status(1) // 默认显示，可根据业务需求调整为待审核
                .images(finalImageUrls.isEmpty() ? null : JSON.toJSONString(finalImageUrls))
                .build();

        this.save(comment);

        log.info("创建商品评价成功");
    }

    @Override
    public Page<CommentVO> getUserComments(Long userId, CommentQueryDTO queryDTO) {
        log.info("获取用户评价列表: userId={}, current={}, size={}", userId, queryDTO.getCurrent(), queryDTO.getSize());

        // 构建查询条件
        LambdaQueryWrapper<ProductComment> queryWrapper = new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getUserId, userId)
                .eq(ProductComment::getIsDeleted, 0)
                .orderByDesc(ProductComment::getCreateTime);

        // 商品ID筛选
        if (queryDTO.getProductId() != null) {
            queryWrapper.eq(ProductComment::getProductId, queryDTO.getProductId());
        }

        // 评分筛选
        if (queryDTO.getRating() != null) {
            queryWrapper.eq(ProductComment::getRating, queryDTO.getRating());
        }

        // 分页查询
        Page<ProductComment> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        Page<ProductComment> commentPage = this.page(page, queryWrapper);

        // 转换为VO并返回
        return (Page<CommentVO>) commentPage.convert(this::convertToCommentVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteComment(Long userId, Long commentId) {
        log.info("删除评价");

        // 查询评论
        ProductComment comment = this.getById(commentId);
        if (comment == null || comment.getIsDeleted() == 1) {
            CommentException.commentNotFound();
        }

        // 检查权限
        if (!comment.getUserId().equals(userId)) {
            CommentException.commentNotAllowed();
        }

        // 软删除
        comment.setIsDeleted(1);
        this.updateById(comment);

        log.info("删除评价成功");
    }

    @Override
    public PageResult<AdminCommentVO> getAdminCommentList(CommentQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<ProductComment> queryWrapper = new LambdaQueryWrapper<>();

        // 商品ID筛选
        if (queryDTO.getProductId() != null) {
            queryWrapper.eq(ProductComment::getProductId, queryDTO.getProductId());
        }

        // 商品名称搜索 - 需要关联查询
        if (StringUtils.hasText(queryDTO.getProductName())) {
            // 先查询符合条件的商品ID
            List<Long> productIds = productMapper.selectList(
                    new LambdaQueryWrapper<Product>()
                            .like(Product::getName, queryDTO.getProductName())
                            .select(Product::getId)
            ).stream().map(Product::getId).toList();

            if (!productIds.isEmpty()) {
                queryWrapper.in(ProductComment::getProductId, productIds);
            } else {
                // 如果没有找到匹配的商品，返回空结果
                queryWrapper.eq(ProductComment::getId, -1);
            }
        }

        // 用户ID筛选
        if (queryDTO.getUserId() != null) {
            queryWrapper.eq(ProductComment::getUserId, queryDTO.getUserId());
        }

        // 用户名搜索 - 需要关联查询
        if (StringUtils.hasText(queryDTO.getUsername())) {
            // 先查询符合条件的用户ID
            List<Long> userIds = userMapper.selectList(
                    new LambdaQueryWrapper<User>()
                            .like(User::getUsername, queryDTO.getUsername())
                            .select(User::getId)
            ).stream().map(User::getId).toList();

            if (!userIds.isEmpty()) {
                queryWrapper.in(ProductComment::getUserId, userIds);
            } else {
                // 如果没有找到匹配的用户，返回空结果
                queryWrapper.eq(ProductComment::getId, -1);
            }
        }

        // 评论内容搜索
        if (StringUtils.hasText(queryDTO.getContent())) {
            queryWrapper.like(ProductComment::getContent, queryDTO.getContent());
        }

        // 评分筛选
        if (queryDTO.getRating() != null) {
            queryWrapper.eq(ProductComment::getRating, queryDTO.getRating());
        }

        // 是否有图片筛选
        if (queryDTO.getHasImages() != null) {
            if (queryDTO.getHasImages() == 1) {
                queryWrapper.isNotNull(ProductComment::getImages);
                queryWrapper.ne(ProductComment::getImages, "");
            } else {
                queryWrapper.and(wrapper -> wrapper.isNull(ProductComment::getImages)
                        .or().eq(ProductComment::getImages, ""));
            }
        }

        // 是否匿名筛选
        if (queryDTO.getIsAnonymous() != null) {
            queryWrapper.eq(ProductComment::getIsAnonymous, queryDTO.getIsAnonymous());
        }

        // 状态筛选
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(ProductComment::getStatus, queryDTO.getStatus());
        }

        // 是否有回复筛选
        if (queryDTO.getHasReply() != null) {
            if (queryDTO.getHasReply() == 1) {
                queryWrapper.isNotNull(ProductComment::getReplyContent);
                queryWrapper.ne(ProductComment::getReplyContent, "");
            } else {
                queryWrapper.and(wrapper -> wrapper.isNull(ProductComment::getReplyContent)
                        .or().eq(ProductComment::getReplyContent, ""));
            }
        }

        // 时间范围筛选
        if (queryDTO.getStartTime() != null) {
            queryWrapper.ge(ProductComment::getCreateTime, queryDTO.getStartTime());
        }
        if (queryDTO.getEndTime() != null) {
            queryWrapper.le(ProductComment::getCreateTime, queryDTO.getEndTime());
        }

        // 动态排序 - 支持更多排序字段
        boolean isAsc = "asc".equalsIgnoreCase(queryDTO.getSortOrder());
        switch (queryDTO.getSortBy()) {
            case "rating":
                queryWrapper.orderBy(true, isAsc, ProductComment::getRating);
                break;
            case "replyTime":
                queryWrapper.orderBy(true, isAsc, ProductComment::getReplyTime);
                break;
            case "updateTime":
                queryWrapper.orderBy(true, isAsc, ProductComment::getUpdateTime);
                break;
            case "createTime":
            default:
                // 默认按创建时间排序
                queryWrapper.orderBy(true, isAsc, ProductComment::getCreateTime);
                break;
        }

        // 确保删除的评论不会被查询到
        queryWrapper.eq(ProductComment::getIsDeleted, 0);

        // 分页查询
        Page<ProductComment> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        Page<ProductComment> commentPage = this.page(page, queryWrapper);

        // 使用PageResult.of方法进行转换
        return PageResult.of(commentPage, this::convertToAdminCommentVO);
    }

    @Override
    public AdminCommentVO getAdminCommentDetail(Long commentId) {
        ProductComment comment = this.getById(commentId);
        if (comment == null) {
            CommentException.commentNotFound();
        }

        return convertToAdminCommentVO(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCommentStatus(Long commentId, CommentUpdateStatusDTO dto) {
        // 获取评论信息
        ProductComment comment = this.getById(commentId);
        if (comment == null) {
            CommentException.commentNotFound();
            return;
        }

        // 更新评论状态
        LambdaUpdateWrapper<ProductComment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProductComment::getId, commentId);
        updateWrapper.set(ProductComment::getStatus, dto.getStatus());

        this.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void replyComment(Long commentId, CommentReplyDTO dto) {
        // 获取评论信息
        ProductComment comment = this.getById(commentId);
        if (comment == null) {
            CommentException.commentNotFound();
            return;
        }

        // 更新回复内容
        LambdaUpdateWrapper<ProductComment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProductComment::getId, commentId);
        updateWrapper.set(ProductComment::getReplyContent, dto.getReplyContent());
        updateWrapper.set(ProductComment::getReplyTime, LocalDateTime.now());

        this.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateCommentStatus(CommentBatchUpdateStatusDTO dto) {
        // 批量更新评论状态
        LambdaUpdateWrapper<ProductComment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(ProductComment::getId, dto.getCommentIds());
        updateWrapper.set(ProductComment::getStatus, dto.getStatus());

        this.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteComments(List<Long> commentIds) {
        log.info("批量删除评论");

        // 批量软删除评论
        LambdaUpdateWrapper<ProductComment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(ProductComment::getId, commentIds);
        updateWrapper.set(ProductComment::getIsDeleted, 1);

        this.update(updateWrapper);

        log.info("批量删除评论成功");
    }

    @Override
    public CommentStatisticsVO getAdminProductCommentStatistics(Long productId) {
        log.info("获取商品评论统计信息: productId={}", productId);

        // 查询该商品的所有评论（包括隐藏的）
        List<ProductComment> comments = this.list(new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getProductId, productId)
                .eq(ProductComment::getIsDeleted, 0));

        long totalComments = comments.size();
        long todayComments = comments.stream()
                .filter(comment -> comment.getCreateTime().toLocalDate().equals(LocalDate.now()))
                .count();
        long publishedComments = comments.stream()
                .filter(comment -> comment.getStatus() == 1)
                .count();
        long hiddenComments = comments.stream()
                .filter(comment -> comment.getStatus() == 0)
                .count();
        long repliedComments = comments.stream()
                .filter(comment -> StringUtils.hasText(comment.getReplyContent()))
                .count();

        // 计算各星级评论数
        long fiveStarCount = comments.stream().filter(c -> c.getRating() == 5).count();
        long fourStarCount = comments.stream().filter(c -> c.getRating() == 4).count();
        long threeStarCount = comments.stream().filter(c -> c.getRating() == 3).count();
        long twoStarCount = comments.stream().filter(c -> c.getRating() == 2).count();
        long oneStarCount = comments.stream().filter(c -> c.getRating() == 1).count();

        // 计算平均评分
        BigDecimal avgRating = BigDecimal.ZERO;
        if (totalComments > 0) {
            double average = comments.stream()
                    .mapToInt(ProductComment::getRating)
                    .average()
                    .orElse(0.0);
            avgRating = BigDecimal.valueOf(average).setScale(2, RoundingMode.HALF_UP);
        }

        // 使用Builder模式构建统计VO
        return CommentStatisticsVO.builder()
                .totalComments(totalComments)
                .todayComments(todayComments)
                .pendingReview(0L) // 商品维度不需要待审核概念
                .publishedComments(publishedComments)
                .hiddenComments(hiddenComments)
                .repliedComments(repliedComments)
                .avgRating(avgRating)
                .fiveStarCount(fiveStarCount)
                .fourStarCount(fourStarCount)
                .threeStarCount(threeStarCount)
                .twoStarCount(twoStarCount)
                .oneStarCount(oneStarCount)
                .build();
    }

    @Override
    public CommentStatisticsVO getAdminCommentStatistics() {
        // 查询所有评论
        List<ProductComment> comments = this.list(new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getIsDeleted, 0));

        // 统计各种数据
        long totalComments = comments.size();
        long todayComments = comments.stream()
                .filter(comment -> comment.getCreateTime().toLocalDate().equals(LocalDate.now()))
                .count();
        long pendingReview = comments.stream()
                .filter(comment -> comment.getStatus() == 0)
                .count();
        long publishedComments = comments.stream()
                .filter(comment -> comment.getStatus() == 1)
                .count();
        long hiddenComments = comments.stream()
                .filter(comment -> comment.getStatus() == 0)
                .count();
        long repliedComments = comments.stream()
                .filter(comment -> StringUtils.hasText(comment.getReplyContent()))
                .count();

        // 使用Builder模式构建统计VO
        return CommentStatisticsVO.builder()
                .totalComments(totalComments)
                .todayComments(todayComments)
                .pendingReview(pendingReview)
                .publishedComments(publishedComments)
                .hiddenComments(hiddenComments)
                .repliedComments(repliedComments)
                .build();
    }


    @Override
    public CommentStatisticsVO getCommentStatistics(Long productId) {
        log.info("获取商品评价统计: productId={}", productId);

        // 查询该商品的所有评论
        List<ProductComment> comments = this.list(new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getProductId, productId)
                .eq(ProductComment::getStatus, 1) // 只统计显示的评论
                .eq(ProductComment::getIsDeleted, 0));

        // 统计各种数据
        long totalComments = comments.size();
        long fiveStarCount = comments.stream().filter(c -> c.getRating() == 5).count();
        long fourStarCount = comments.stream().filter(c -> c.getRating() == 4).count();
        long threeStarCount = comments.stream().filter(c -> c.getRating() == 3).count();
        long twoStarCount = comments.stream().filter(c -> c.getRating() == 2).count();
        long oneStarCount = comments.stream().filter(c -> c.getRating() == 1).count();

        // 计算平均评分
        BigDecimal avgRating = totalComments > 0 ?
                BigDecimal.valueOf(comments.stream().mapToInt(ProductComment::getRating).average().orElse(0.0))
                        .setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO;

        // 使用Builder模式构建统计VO
        return CommentStatisticsVO.builder()
                .totalComments(totalComments)
                .avgRating(avgRating)
                .fiveStarCount(fiveStarCount)
                .fourStarCount(fourStarCount)
                .threeStarCount(threeStarCount)
                .twoStarCount(twoStarCount)
                .oneStarCount(oneStarCount)
                .build();
    }

    @Override
    public boolean checkUserCommented(Long userId, Long productId) {
        log.info("检查用户是否已评论商品");

        long count = this.count(new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getUserId, userId)
                .eq(ProductComment::getProductId, productId)
                .eq(ProductComment::getIsDeleted, 0));

        boolean hasCommented = count > 0;
        log.info("用户评论检查结果");
        return hasCommented;
    }

    @Override
    public Map<Long, Boolean> getOrderItemsCommentStatus(Long userId, Long orderId) {
        log.info("获取订单商品评论状态: userId={}, orderId={}", userId, orderId);

        // 获取订单中的所有商品ID
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderId));

        Map<Long, Boolean> commentStatusMap = new HashMap<>();

        for (OrderItem item : orderItems) {
            // 检查用户是否对该订单中的该商品进行过评价
            boolean hasCommented = checkUserCommentedForOrder(userId, item.getProductId(), orderId);
            commentStatusMap.put(item.getProductId(), hasCommented);
        }

        log.info("订单商品评论状态获取完成: userId={}, orderId={}, statusMap={}", userId, orderId, commentStatusMap);
        return commentStatusMap;
    }

    /**
     * 检查用户是否对特定订单中的特定商品进行过评价
     */
    private boolean checkUserCommentedForOrder(Long userId, Long productId, Long orderId) {
        log.info("检查用户是否已评论订单商品: userId={}, productId={}, orderId={}", userId, productId, orderId);

        long count = this.count(new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getUserId, userId)
                .eq(ProductComment::getProductId, productId)
                .eq(ProductComment::getOrderId, orderId)
                .eq(ProductComment::getIsDeleted, 0));

        boolean hasCommented = count > 0;
        log.info("用户订单商品评论检查结果: userId={}, productId={}, orderId={}, hasCommented={}",
                userId, productId, orderId, hasCommented);
        return hasCommented;
    }


    /**
     * 转换ProductComment为CommentVO（统一转换方法）
     */
    private CommentVO convertToCommentVO(ProductComment comment) {
        // 解析图片JSON
        List<String> imageList = new ArrayList<>();
        if (StringUtils.hasText(comment.getImages())) {
            try {
                imageList = JSON.parseArray(comment.getImages(), String.class);
            } catch (Exception e) {
                imageList = new ArrayList<>();
            }
        }

        // 获取用户显示信息
        String[] userInfo = getUserDisplayInfo(comment.getUserId(), comment.getIsAnonymous());

        // 使用Builder模式构建CommentVO
        return CommentVO.builder()
                .id(comment.getId())
                .productId(comment.getProductId())
                .userId(comment.getUserId())
                .orderId(comment.getOrderId())
                .content(comment.getContent())
                .rating(comment.getRating())
                .images(imageList)
                .replyContent(comment.getReplyContent())
                .replyTime(comment.getReplyTime())
                .isAnonymous(comment.getIsAnonymous())
                .status(comment.getStatus())
                .createTime(comment.getCreateTime())
                .updateTime(comment.getUpdateTime())
                .username(userInfo[0])
                .userAvatar(userInfo[1])
                .build();
    }

    /**
     * 转换ProductComment为AdminCommentVO（管理端专用）
     * 严格基于数据库表结构进行数据组装
     */
    private AdminCommentVO convertToAdminCommentVO(ProductComment comment) {
        // 解析图片JSON
        List<String> imageList = new ArrayList<>();
        if (StringUtils.hasText(comment.getImages())) {
            try {
                imageList = JSON.parseArray(comment.getImages(), String.class);
            } catch (Exception e) {
                imageList = new ArrayList<>();
            }
        }

        // 查询用户信息（来自user表）
        User user = userMapper.selectById(comment.getUserId());
        String username = "用户不存在";
        String userAvatar = "";
        Integer userStatus = 0;

        if (user != null) {
            userStatus = user.getStatus();

            if (comment.getIsAnonymous() != null && comment.getIsAnonymous() == 1) {
                username = "匿名用户";
                userAvatar = "";
            } else {
                username = user.getUsername();
                userAvatar = user.getAvatar() != null ? user.getAvatar() : "";
            }
        }

        // 查询商品信息（来自product表）
        Product product = productMapper.selectById(comment.getProductId());
        String productName = "商品不存在";
        String productMainImage = "";
        BigDecimal productPrice = BigDecimal.ZERO;
        String productBrand = "";
        Integer productStatus = 0;

        if (product != null) {
            productName = product.getName();
            productMainImage = product.getMainImage();
            productPrice = product.getPrice();
            productBrand = product.getBrand();
            productStatus = product.getStatus();
        }

        // 不查询订单相关信息，简化业务逻辑

        // 使用Builder模式构建AdminCommentVO
        return AdminCommentVO.builder()
                // 评论基础信息
                .id(comment.getId())
                .productId(comment.getProductId())
                .userId(comment.getUserId())
                .orderId(comment.getOrderId())
                .content(comment.getContent())
                .rating(comment.getRating())
                .images(imageList)
                .replyContent(comment.getReplyContent())
                .replyTime(comment.getReplyTime())
                .isAnonymous(comment.getIsAnonymous())
                .status(comment.getStatus())
                .createTime(comment.getCreateTime())
                .updateTime(comment.getUpdateTime())
                // 用户信息
                .username(username)
                .userAvatar(userAvatar)
                .userStatus(userStatus)
                // 商品信息
                .productName(productName)
                .productMainImage(productMainImage)
                .productPrice(productPrice)
                .productBrand(productBrand)
                .productStatus(productStatus)
                .build();
    }

    /**
     * 获取用户显示信息
     *
     * @param userId      用户ID
     * @param isAnonymous 是否匿名
     * @return String数组，[0]为用户名，[1]为头像URL
     */
    private String[] getUserDisplayInfo(Long userId, Integer isAnonymous) {
        if (isAnonymous != null && isAnonymous == 1) {
            // 匿名用户
            return new String[]{"匿名用户", ""};
        } else {
            // 查询用户信息
            User user = userMapper.selectById(userId);
            if (user != null) {
                return new String[]{user.getUsername(), user.getAvatar() != null ? user.getAvatar() : ""};
            } else {
                return new String[]{"用户不存在", ""};
            }
        }
    }

    /**
     * 私有方法：上传评论图片
     * 融入到评论创建业务中，不对外暴露
     */
    private String uploadCommentImage(String imageBase64) {
        // 评论图片上传路径常量
        final String COMMENT_IMAGE_PATH = "images/comment/";

        try {
            log.info("开始上传评论图片");

            // 1. 验证Base64数据格式
            if (imageBase64 == null || !imageBase64.startsWith("data:image/")) {
                log.error("评论图片数据格式不正确");
                FileException.typeNotAllowed();
            }

            // 2. 将Base64数据转换为MultipartFile
            MultipartFile imageFile = Base64MultipartFile.fromBase64(imageBase64);

            // 3. 验证图片文件大小（限制3MB）
            if (imageFile.getSize() > 3 * 1024 * 1024) {
                log.error("评论图片文件过大");
                FileException.sizeExceeded();
            }

            // 4. 使用OSS工具上传图片到指定路径
            String imageUrl = ossUtils.uploadImage(imageFile, COMMENT_IMAGE_PATH);

            // 5. 验证上传结果
            if (imageUrl == null || imageUrl.isEmpty()) {
                log.error("OSS上传返回空URL");
                FileException.uploadFailed();
            }

            log.info("评论图片上传成功");
            return imageUrl;

        } catch (Exception e) {
            log.error("评论图片上传失败: error={}", e.getMessage(), e);
            // 重新抛出异常，不返回null
            if (e instanceof RuntimeException) {
                throw e;
            }
            FileException.uploadFailed();
            return null; // 这行不会执行，因为上面会抛异常
        }
    }
}
